import { Ray3, IntersectResult, Vector3, Phong } from "@script/index";

export default class Sphere {
  private sqrRadius: number;
  private readonly center: Vector3;
  private readonly radius: number;
  material: Phong;

  constructor(center: Vector3, radius: number) {
    this.center = center;
    this.radius = radius;
  }

  initialize(): void {
    this.sqrRadius = this.radius * this.radius;
  }

  copy() {
    return new Sphere(this.center.copy(), this.radius);
  }

  intersect(ray: Ray3): IntersectResult {
    let vector3 = ray.origin.subtract(this.center);
    let a0 = vector3.sqrLength() - this.sqrRadius;
    let dot_v = ray.direction.dot(vector3);
    if (dot_v <= 0) {
      let dis = dot_v * dot_v - a0;
      if (dis >= 0) {
        let result: IntersectResult = new IntersectResult();
        result.geometry = this;
        result.distance = -dot_v - Math.sqrt(dis);
        result.position = ray.point(result.distance);
        result.normal = result.position.subtract(this.center).normalize();
        return result;
      }
    }
    return IntersectResult.noHit;
  }

}